/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package interface_;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author TUAN ANH
 */
public class Server implements TranferData {

    private Socket receiveSocket; // socket 
    private ServerSocket serverSocket; // server
    private BufferedReader bufferedReader; // input stream
    private DataOutputStream dataOutputStream; // outputstream
    private int port;
//    String localhost;

    public Server(int port) {
//        this.localhost = localhost;
        this.port = port;
    }

    @Override
    public void initConnection() {
        try {
            this.serverSocket = new ServerSocket(port);
            this.receiveSocket = serverSocket.accept();
            this.bufferedReader = new BufferedReader(new InputStreamReader(receiveSocket.getInputStream()));
            this.dataOutputStream = new DataOutputStream(receiveSocket.getOutputStream());
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }

    @Override
    public String receiveData() {
        String stringReceive = "";
        try {
            stringReceive = bufferedReader.readLine();
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
        return stringReceive;
    }

    @Override
    public void sentData(String data) {
//        throw new UnsupportedOperationException("Not supported yet.");
        try {
            for (int i = 0; i < data.length(); i++) {
                dataOutputStream.write((byte) data.charAt(i));
            }
            dataOutputStream.write(13);
            dataOutputStream.flush();
        } catch (Exception ex) {
        }
    }

    @Override
    public void close() {
//        throw new UnsupportedOperationException("Not supported yet.");
        try {
            serverSocket.close();
            receiveSocket.close();
            bufferedReader.close();
            dataOutputStream.close();
        } catch (Exception ex) {
        }
    }
}
